<template>
	<statusBarVue title="登录" :isShowBar="true" :isShowLeft="true" :isMyBgi="true" />
	<view class="login-page" :style="pageHaveBarStyle">
		<view v-if="isUserLoginForm" class="login-page-form">
			<view class="login-page-group">
				<uni-forms ref="form" :rules="rules" :model="formData">
					<uni-forms-item label="手机号" name="loginId" required>
						<uni-easyinput v-model="formData.loginId" placeholder="请输入" primaryColor="#22A366" />
					</uni-forms-item>
					<uni-forms-item label="密码" name="passwd" required>
						<uni-easyinput type="password" v-model="formData.passwd" placeholder="请输入" primaryColor="#22A366" />
					</uni-forms-item>
				</uni-forms>
				<view class="submit-btn">
					<button style="color:#ffffff;backgroundColor:#22A366;" @click="handleLoginForm">登 录</button>
				</view>
			</view>
		</view>
		<view v-else>
			<view class="login-page-group">
				<image src="" mode=""></image>
				<view>申请获取以下权限:</view>
				<view class="list">
					<view class="list-i">获取用户手机号</view>
					<view class="list-i">查看用户位置信息</view>
				</view>
			</view>
			<view class="login-page-group">
				<button class="login-btn" @getphonenumber="handleGetPhoneNumber" open-type="getPhoneNumber"
					:disabled="wxLoginBtnDis">
					<text>手机号快捷登录</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import statusBarVue from '@/components/statusBar.vue';

import {
	getWechatToken,
	getForumsList,
	getPhone,
	getCheckExists,
	postAddRegister,
	postLogin
} from '@/utils/api.js';

import {
	publics
} from '@/mixins/publics.js';

export default {
	mixins: [publics],
	components: {
		statusBarVue
	},
	data() {
		return {
			isUserLoginForm: false, // 当手机号码被占时显示 使用 手机号密码登录
			wxLoginBtnDis: true, // 微信一键登录 是否能点击
			loginCode: '', // uni.login 的 code
			msg: {}, // 用户基本信息
			openId: '',
			formData: {
				loginId: '',
				passwd: ''
			},
			rules: {
				loginId: {
					rules: [{
						required: true,
						errorMessage: '手机号码不能为空',
					}, {
						validateFunction: function (rule, value, data, callback) {
							const phonePattern = /^1\d{10}$/;
							if (!(phonePattern.test(value))) {
								callback('手机号码格式错误')
							}
							return true
						}
					}]
				},
				passwd: {
					rules: [{
						required: true,
						errorMessage: '密码不能为空',
					}]
				}
			}
		}
	},
	created() {
		this.handleAutoLogin();
	},
	methods: {
		handleLoginForm() {
			this.$refs.form.validate((err, formData) => {
				if (!err) {
					const {
						loginId,
						passwd
					} = {
						...formData
					}
					const registerData = {
						loginId,
						openId: this.openId,
						passwd
					};

					postLogin(registerData).then(
						req => {
							if (req.code === 200) {
								uni.setStorageSync(
									'_token',
									req.data.token.token
								);
								uni.showToast({
									icon: 'success',
									title: '登录成功'
								});
								uni.navigateBack();

							} else {
								uni.showToast({
									icon: 'error',
									title: req.detail
								});
							}
						}
					)
				}
			})
		},

		// 微信自动登录
		handleAutoLogin() {
			uni.showLoading({
				title: "请稍后",
				mask: true
			});

			uni.login({
				success: (loginRes) => {
					uni.getUserInfo({
						desc: '授权并获取用户基本信息。',
						success: (msg) => {
							console.log("用户基本信息 ---->>>", msg)
							const postData = {
								code: loginRes.code
							};
							this.loginCode = loginRes.code;
							this.msg = msg;
							// 获取 openId 
							this.getWechatTokenApi(postData, msg)
						},
						fail: (err) => {
							console.error(err);
							uni.hideLoading();
							this.wxLoginBtnDis = false; // 放开获取手机号登录
						}
					})
				},
				fail: (info) => {
					uni.hideLoading();
					this.wxLoginBtnDis = false; // 放开获取手机号登录
					uni.showToast({
						duration: 5000,
						title: 'login fail --->>' + JSON.stringify(info)
					})
				}
			})
		},

		// 获取 openId 
		getWechatTokenApi(postData, msg) {
			getWechatToken(postData).then(res => {
				uni.hideLoading();

				if (res.code === 200) {
					const _userInfo = res.data.user;

					this.openId = res.data.open_id;
					// 判断 User 是否为空，空转为注册，非空直接登录
					if (res.data.user.id) {
						uni.setStorageSync(
							'_token',
							res.data.token.token
						);

						uni.setStorageSync(
							'_userInfo',
							_userInfo
						);
						uni.hideLoading();
						uni.navigateBack();
					} else {
						this.wxLoginBtnDis = false; // 放开获取手机号登录
					}
				}
			})
		},

		// 获取手机号
		handleGetPhone(phoneData, phoneInfo, msg, openId) {
			// 获取手机号
			getPhone(phoneData).then(res => {
				if (res.code === 200) {
					let postData = {
						code: res.data.data.phoneNumber
					};
					msg.userInfo.phoneData = res.data.data.phoneNumber; // 获取手机号

					this.getCheckExistsApi(postData, phoneInfo, msg, openId);
				}
			}).catch(req => {
				uni.showToast({
					title: 'getPhone API req >>' + JSON.stringify(res)
				})
			})
		},

		// 检测是否登陆ID（手机号）是否存在
		getCheckExistsApi(postData, phoneInfo, msg, openId) {
			getCheckExists(postData.code).then((req) => {
				if (req.code === 200) {
					if (req.data.if_exists === 0) {
						// 去注册
						this.handleRegister(msg, openId);
					} else {
						// 账号被其他设备占用  使用密码登录
						this.isUserLoginForm = true;
					}
				}
			})
		},

		// 去注册
		handleRegister(msg, openId) {
			uni.showModal({
				title: '提示',
				content: '您还未注册, 是否前往注册',
				success: function (type) {
					if (type.confirm) {
						// 去注册
						const registerDataStr = {
							avatar: msg.userInfo.avatarUrl,
							nickName: msg.userInfo.nickName,
							loginId: msg.userInfo.phoneData,
							openId
						};

						uni.navigateTo({
							url: `/pages/register/register?registerDataStr=${JSON.stringify(registerDataStr)}`
						});
					}
				}
			});
		},

		// 获取用户手机号
		handleGetPhoneNumber(info) {
			let _this = this;
			const phoneInfo = info.detail;
			// 判断是否成功获取手机号信息
			if (phoneInfo.encryptedData) {
				uni.login({
					success: (loginRes) => {
						const phoneData = {
							code: loginRes.code,
							encryptedData: phoneInfo.encryptedData,
							iv: phoneInfo.iv
						};
						// 读取手机号
						_this.handleGetPhone(phoneData, phoneInfo, _this.msg, _this.openId);
					}
				})

			} else {
				wx.getSetting({
					success(res) {
						if (res.authSetting['scope.userInfo']) {
							// 已经授权，可以直接调用 getUserInfo 获取头像昵称
							uni.getUserInfo({
								desc: '用于完善个人资料。',
								success: (msg) => {
									const postData = {
										code: _this.loginCode
									};
									// 去注册
									_this.handleRegister(msg, _this.openId);
								},
								fail: (info) => {
									console.log("info ----->>>", info)
									uni.showToast({
										duration: 5000,
										title: 'getUserInfo fail ---->>>' + JSON.stringify(
											info)
									})
								}
							})

						}
					},
					fail(req) {
						console.log("req =======>>>", req)
						uni.showToast({
							duration: 5000,
							title: 'getSetting fail ---->>>' + JSON.stringify(req)
						})
					}
				})
			}

		}
	}
}
</script>

<style lang="scss">
.login-page {
	margin: auto;
	position: fixed;
	left: 0;
	right: 0;
	z-index: 99;
	background-color: #F2F3F7;
	padding: 16px 3.66vw;
	box-sizing: border-box;

	.login-page-form {
		width: calc(100vw - 3.66vw - 3.66vw);
		position: absolute;
		bottom: 0;
		top: 0;
		margin: auto;
		left: 0;
		right: 0;
		height: 25vh;
	}

	.login-page-group {
		margin-bottom: 12px;

		.list {
			.list-i {
				height: 22px;
				line-height: 20px;
				text-indent: 2ch;

				&::before {
					display: inline-block;
					content: "";
					width: 6px;
					height: 6px;
					border-radius: 6px;
					margin-right: 10px;
					vertical-align: middle;
					background-color: #000;
				}
			}
		}

		.login-btn {
			background-color: #22A366;
			line-height: 1.8;
			display: flex;
			align-items: center;
			justify-content: center;

			text {
				font-size: 22px;
				font-weight: bold;
				margin-left: 10px;
				color: #ffffff;
			}
		}
	}

}
</style>